<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
namespace common\behavior;

use common\model\TenantUserModel;
use common\service\OauthService;

/**
 * 行为扩展：处理event
 */
class NotifyTenantUserStatusChangedBehavior
{
    private OauthService $oauthService;

    public function __construct()
    {
        $this->oauthService = new OauthService();
    }

    /**
     * 处理记录event log
     * @param $params
     */
    public function run(&$params)
    {
        APP_DEBUG && trace("occur " . __CLASS__, "DEBUG");
        try {
            if (empty($params['data']['old']['status']) || empty($params['data']['new']['status'])) {
                return;
            }
            $oldStatus = $params['data']['old']['status'];
            $newStatus = $params['data']['new']['status'];
            $tenantUser = model(TenantUserModel::class)->find($params['primary_id']);
            if ($oldStatus === 'invalid' && $newStatus === 'active') {
                // 切租户了
                $this->oauthService->sendDataToUserChannel([
                    'param' => [
                        'filter' => ['id' => $tenantUser['user_id'],],
                        'data' => [
                            'event_key' => 'tenant_user_status_changed',
                            'event_data' => $tenantUser,
                        ]
                    ]
                ]);
            } elseif ($oldStatus === TenantUserModel::STATUS_ACTIVE && $newStatus === TenantUserModel::STATUS_UNEMPLOYED) {
                // 当前在公司 并且离职了 就通知用户离职了
                $this->oauthService->sendDataToUserChannel([
                    'param' => [
                        'filter' => ['id' => $tenantUser['user_id'],],
                        'data' => [
                            'event_key' => 'tenant_user_status_unemployed',
                            'event_data' => $tenantUser,
                        ]
                    ]
                ]);
            }
        } catch (\Throwable $e) {
            trace(format_exception_info($e), 'ERR');
        }
    }
}
